package org.noahsark.core.util;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;

/**
 * Resource Message.
 */
public class ResourceMessage {

    private static Log log = LogFactory.getLog(ResourceMessage.class);

    private static final String IOS_CONFIGURATION_FILE = "ios.properties";
    private static final String IOS_RESOURCE_MESSAGES = "ios.resource.messages";

    private static List<ResourceBundle> resourceBundles = new ArrayList<ResourceBundle>();

    private ResourceMessage() {

    }

    static {
    	log.info("######################");
        Configuration config;
        try {
            config = new PropertiesConfiguration(IOS_CONFIGURATION_FILE);
            List<Object> resourceNames = config.getList(IOS_RESOURCE_MESSAGES);

            if (resourceNames == null) {
                log.error("Not specify resource message files!");
            } else {
                for (Object resourceName : resourceNames) {

                    try {
                        log.info("Loding resource message file: " + (String) resourceName + ".properties");
                        resourceBundles.add(ResourceBundle.getBundle((String) resourceName, Locale.US));
                    } catch (MissingResourceException ex) {
                        log.warn(ex);
                    }
                }
            }
        } catch (ConfigurationException ex) {
            log.error(ex);
        }

    }

    /**
     * add resource bundle.
     * 
     * @param bundele - resource bundle
     */
    public static void addResourceBundle(ResourceBundle bundele) {
        resourceBundles.add(bundele);
    }

    /**
     * get message from resource file by key.
     * 
     * @param key - key in resource file
     * @param params - the parameters used for replacing the placeholders of message in resource
     *            file
     * @return formatted message
     */
    public static String getMessage(String key, String... params) {
        for (ResourceBundle resourceBundle : resourceBundles) {
            if (resourceBundle.containsKey(key)) {
                return MessageFormat.format(resourceBundle.getString(key), params);
            }
        }
        return key;
    }
}
